import 'package:base_flutter_project/model/card_model_item.dart';
import 'package:base_flutter_project/network/network.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
// import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class CardPageDetail extends StatefulWidget {
  final String travelurl;
  final String groupChannelCode;

  const CardPageDetail(
      {Key key, this.travelurl, this.groupChannelCode})
      : super(key: key);

  @override
  _CardPageDetailState createState() => _CardPageDetailState();
}

class _CardPageDetailState extends State<CardPageDetail> with AutomaticKeepAliveClientMixin{
  List<ResultList> list;
  int pageIndex = 1;
  RefreshController _refreshController;
  @override
  void initState() {
    _loadData();
    _refreshController = RefreshController(initialRefresh: false);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: WaterDropHeader(),
      footer: CustomFooter(
          builder: (BuildContext context,LoadStatus mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("pull up load");
            }
            else if(mode==LoadStatus.loading){
              body = CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("Load Failed!Click retry!");
            }
            else if(mode == LoadStatus.canLoading){
                body = Text("release to load more");
            }
            else{
              body = Text("No more Data");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
      controller: _refreshController,
      onLoading: _onLoadMore,
      onRefresh: _loadData,
      child: StaggeredGridView.countBuilder(
        crossAxisCount: 4,
        itemCount: list?.length??0,
        itemBuilder: (BuildContext context, int index) => _TravelItem(index: index,item: list[index]),
        staggeredTileBuilder: (int index) =>
            new StaggeredTile.fit(2),
        mainAxisSpacing: 4.0,
        crossAxisSpacing: 4.0,
      ),
    );
  }

  void _loadData() {
    pageIndex = 1;
    Network.card_item_fetch(widget.travelurl, widget.groupChannelCode, pageIndex, 10)
        .then((res) {
      setState(() {
        list = res.resultList;
      });
      _refreshController.refreshCompleted();
    }).catchError((e) {
      _refreshController.refreshFailed();
    });
  }

  void _onLoadMore() {
    pageIndex += 1;
    Network.card_item_fetch(widget.travelurl, widget.groupChannelCode, pageIndex, 10)
        .then((res) {
      setState(() {
        list.addAll(res.resultList);
      });
      if(res.resultList.length < 10){
        _refreshController.loadNoData();
      } else {
        _refreshController.loadComplete();
      }
    }).catchError((e) {
      _refreshController.loadFailed();
      print(e);
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class _TravelItem extends StatelessWidget {
  
  final ResultList item;
  final int index;

  const _TravelItem({Key key, this.item, this.index}) : super(key: key);

  String _posiName(){
    return item.article.poiName == null || item.article.poiName.length == 0 ? "未知" : item.article.poiName;
  }

  String _imageURL() {

  }

  Widget _itemImage(){
    return Stack(
      children: <Widget>[
        Image.network(item.article.images[0]?.dynamicUrl ?? ""),
        Positioned(
          bottom: 5,
          left: 5,
          child: Container(
            height: 20,
            padding: const EdgeInsets.fromLTRB(5, 1, 5, 1),
            decoration: BoxDecoration(
              color: Colors.black45,
              borderRadius: BorderRadius.circular(10)
            ),
            child: Row(
              children: <Widget>[
                Icon(Icons.location_on,color: Colors.white,size: 15,),
                LimitedBox(
                  maxWidth: 130,
                  child: Text(
                    item.article.poiName,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Colors.white,fontSize: 10),),
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  Widget _createAvatar(){
    return Container(
      padding: const EdgeInsets.fromLTRB(5, 10, 5, 15),
      child: Row(
        children: <Widget>[
          Container(
            height: 30,
            width: 30,
            child: CircleAvatar(
              backgroundImage: NetworkImage(item.article.author.coverImage.dynamicUrl),
            ),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(left: 5,right: 5),
              child: Text(
                item.article.author.nickName,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          Row(
            children: <Widget>[
              Icon(Icons.thumb_up,color: Colors.grey,size: 15),
              SizedBox(width: 5,),
              Text("${item.article.likeCount}",style: TextStyle(color: Colors.grey,fontSize: 12),)
            ],
          )
        ],
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      clipBehavior: Clip.antiAlias,
      child: PhysicalModel(
        color: Colors.transparent,
        child: Column(
          children: <Widget>[
            _itemImage(),
            Container(
              padding: EdgeInsets.all(4),
              alignment: Alignment.centerLeft,
              child: Text(
                item.article.articleTitle,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 13),
              ),
            ),
            _createAvatar()
          ],
        ),
      ),
    );
  }
}
